package main

import (
	"context"
	"log"
	"os"
	"time"

	pb "go-grpc/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const (
	address     = "localhost:50051"
	defaultName = "世界"
)

func main() {
	// 设置连接服务器
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	// 设置超时上下文
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// 获取命令行参数作为名字，如果没有则使用默认值
	name := defaultName
	if len(os.Args) > 1 {
		name = os.Args[1]
	}

	// 调用 SayHello
	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
	if err != nil {
		log.Fatalf("调用失败: %v", err)
	}
	log.Printf("收到回复: %s", r.GetMessage())
} 